#!/usr/bin/python

import os
import random
import Image
import ImageFont
import ImageDraw
import ImageFilter


capchaDic = {}
def gen_captcha(frontPath, outPth, fnt_sz, fmt='JPEG'):
	global capchaDic

	tfont = {}
	tfont[0] = 'Arial_Black.ttf'
	tfont[1] = 'Arial_Bold.ttf'
	tfont[2] = 'Arial.ttf'
	tfont[3] = 'Times_New_Roman_Bold_Italic.ttf'
	tfont[4] = 'Times_New_Roman_Italic.ttf'
	tfont[5] = 'Arial_Bold_Italic.ttf'
	tfont[6] = 'Arial_Italic.ttf'
	tfont[7] = 'defaultFont.ttf'
	tfont[8] = 'Times_New_Roman_Bold.ttf'
	tfont[9] = 'Times_New_Roman.ttf'
	mc = '0123456789'

	myChoices = 'abcdefghijkmnpqrstuvABCDEFGHJKMNPQRSTUVWXYZ123456789'
	text = ''
	for i in range(6): text += random.choice(myChoices)

	apnd = ''
	for i in range(6): apnd += random.choice(myChoices)
	if not os.path.exists(outPth):
		os.mkdir(outPth)

	file_name = outPth + 'capImg_' + apnd + '.jpg'
	
	fnt = tfont[int( random.choice(mc) ) ] 
	#fnt = '../fonts/' + fnt
	fnt = frontPath + fnt

	fgcolor = random.randint(0,0xffff00) 						# randomly select the foreground color
	bgcolor = fgcolor ^ 0xffffff								# make the background color the opposite of fgcolor
	font = ImageFont.truetype(fnt,fnt_sz)						# create a font object 
	dim = font.getsize(text)									# determine dimensions of the text
	im = Image.new('RGB', (dim[0]+5,dim[1]+5), bgcolor)			# create a new image slightly larger that the text
	d = ImageDraw.Draw(im)
	x, y = im.size
	r = random.randint

	for num in range(30):										# draw 100 random colored boxes on the background
		d.rectangle((r(0,x),r(0,y),r(0,x),r(0,y)),fill=r(0,0xffffff))

	d.text((3,3), text, font=font, fill=fgcolor)				# add the text to the image
	im = im.filter(ImageFilter.EDGE_ENHANCE_MORE)
	im.save(file_name, format=fmt)								# save the image to a file

	capchaDic[file_name] = text
	return file_name


def checkKeyWithFile(fileName, key):
	global capchaDic

	if not os.path.exists(fileName): 
		return False
	if fileName not in capchaDic: 
		return False
	if capchaDic[str(fileName)].lower() == key.lower(): 
		del capchaDic[str(fileName)]
		os.remove(fileName)
		return True
	else: 
		return False


if __name__ == '__main__':
	gen_captcha('../fonts/', '../capImg/yourDomainNameHere/', 32)



#import os
#import sys
#
#import Image, ImageDraw
#import ImageFont
#
#
#
#im = Image.new("RGB", (200,50), 'white')
#draw = ImageDraw.Draw(im)
#
#luxi16 = ImageFont.truetype ( "defaultFont.ttf", 16 )
##luxi12 = ImageFont.truetype ( "defaultFont.ttf", 12 )
#
#
#draw.text([10, 10], 'hello world' , fill=(0,0,0), font=luxi16  )
#im.save("myPicture.png", "PNG")

